package com.archstudy.springcloud.websocket.http;

import com.archstudy.springcloud.common.constants.SessionConstants;
import com.archstudy.springcloud.common.dto.UserDTO;
import com.archstudy.springcloud.common.result.RestOut;
import com.archstudy.springcloud.common.util.JsonUtil;
import com.google.gson.reflect.TypeToken;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;


public class SendSimpleMsgHttpClient {

    String uriString = "/message-dispatcher-provider/api/crazymaker/message/push/v1";
    String host = "127.0.0.1";
    String token =

"eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiIxIiwic2lkIjoiN2JjODU4NDYtNWNjMi00MjRmLWE2Y2ItNmJiZmZhYTA2Njc2IiwiZXhwIjoxNjQ5NDEwMjM1LCJpYXQiOjE2NDkzNzc4MzV9.TOblJWuUa37FJuSFNg0P7L6ZWXeOe1MNIv4iZ78PojNLEwifftstRGa251APjtwCklz4gxaVYz6VJkwFccb5sE8l0IZlCvAQ1DZ1TIE_q2AnIyR6ILrNRHJcFgVjh73cJhJJE8m5_XxpXRmFkFP7-V3xF7kLDftr_MpcJ9_erz9diKHJX41AiRS30Kr-4TopFVYBaQ3U-FkmC5AcIeOqUie4nw38HOAFye7CjzKmYW7jbGjWraqwYi5NMzGeGYth6cLB4BBLV_jvai3joVP7zHo4BuMga5f4_6lg6AtWmN4w_ObjO3loi8ndns_5jYrspZqILqpBfaZeg-pQlOeVeQ";


    int port = 7703;
     Long appId=1L;


    @Test
    public void sendMsg() {



        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<Channel>() {

                        @Override
                        protected void initChannel(Channel channel)
                                throws Exception {
                            //channel.pipeline().addLast(new HttpRequestEncoder());
                            //channel.pipeline().addLast(new HttpResponseDecoder());
                            channel.pipeline().addLast(new HttpClientCodec());
                            channel.pipeline().addLast(new HttpObjectAggregator(65536));
                            channel.pipeline().addLast(new HttpContentDecompressor());
                            channel.pipeline().addLast(new HttpClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }


    public class HttpClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        FullHttpRequest request = buildGetRequest();
            FullHttpRequest request = buildPostRequest();
            ctx.writeAndFlush(request);
        }

        private FullHttpRequest buildPostRequest() throws URISyntaxException {

            // *** 生成post传送的uri

            URI uri = new URI(uriString);

// *** 设置POST数据包中传输的数据 ***

            String content = "{ " +
                    "\"msgId\": \"1234561\"," +
                    " \"appKey\": \"test\"," +
                    " \"targetType\": 1," +
                    " \"targetIds\":\"1860000000\", " +
                    " \"title\":\"title 消息的标题\", " +
                    " \"body\":\"body 消息体\" " +
                    "}";

            byte[] bytes = null;

            try {
                bytes = content.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,

                    uri.toASCIIString(), Unpooled.wrappedBuffer(bytes));

            request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");

            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,

                    request.content().readableBytes());

            request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
            request.headers().set(SessionConstants.AUTHORIZATION_HEAD,token);
            request.headers().set(SessionConstants.USER_IDENTIFIER,appId);

            return request;
        }

        private FullHttpRequest buildGetRequest() throws URISyntaxException {
            URI uri = new URI("/user/get");
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri.toASCIIString());
            request.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            request.headers().add(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
            return request;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg)
                throws Exception {
            System.out.println("msg -> " + msg);
            if (msg instanceof FullHttpResponse) {
                FullHttpResponse response = (FullHttpResponse) msg;
                ByteBuf buf = response.content();
                String result = buf.toString(CharsetUtil.UTF_8);
                System.out.println("response -> " + result);


            }
        }
    }
}